<template>
  <!-- 常见问题 -->
  <div>
    <!-- 页面标题 -->
    <div id="common-problem-title">
      <h1 style="margin-left:50px">常见问题</h1>

    </div>
    <!-- 筛选条件 -->
    <div id="common-problem--select-div">
      <div class="common-problem-select-top">
        <i class="el-icon-set-up"
           style="margin-left:50px"></i>&nbsp;&nbsp;筛选
      </div>
      <div id="common-problem-select-bottom">
        <el-input v-model="tittlesearch"
                  placeholder="输入标题或关键字"
                  style="width:250px;margin-left:50px;float:left"></el-input>
        <div style="height: 100%;
  line-height: 100px;float:left;margin-left:50px">
          上传时间：</div>
        <el-date-picker v-model="selectdate"
                        type="date"
                        placeholder="上传时间"
                        style="float:left;width:200px;margin-left:50px"
                        value-format="yyyy/MM/dd">
        </el-date-picker>
        <div style="height:100%;float:left;margin-left:30px">
          <el-button type="primary"
                     @click="search"
                     round>筛选</el-button>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div id="common-problem-listdiv">
      <div class="common-problem-select-top">
        <i class="el-icon-tickets"
           style="margin-left:50px"></i>&nbsp;&nbsp;问题列表
        <el-button size="mini"
                   @click="handleAdd()"
                   style="margin-left:200px"
                   type="primary">添加问题</el-button>
      </div>
      <!-- 条目展示 -->
      <div id="common-problem-problemlistdiv">
        <el-table ref="multipleTable"
                  :data="tableData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection"
                           width="55">
          </el-table-column>
          <el-table-column prop="tittle"
                           label="标题"
                           width="150">
          </el-table-column>
          <el-table-column prop="classify"
                           label="分类"
                           width="150">
          </el-table-column>
          <el-table-column prop="uploader"
                           label="上传人"
                           width="150">
          </el-table-column>
          <el-table-column prop="uploaddate"
                           label="上传时间"
                           width="150">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini"
                         @click="checkdetail(scope.row)">查看详情</el-button>

              <el-button size="mini"
                         @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini"
                         type="danger"
                         @click="handleDelete(scope.row.id,scope.$index)">删除</el-button>
            </template>

          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.display"
                         :active-value=1
                         :inactive-value=0
                         @change="statusSwitch(scope.row.id,scope.row.display)">
              </el-switch>
            </template>

          </el-table-column>

        </el-table>
        <!-- 查看详情列表 -->
        <el-dialog title="问题详情"
                   :visible.sync="dialogTableVisible">
          <el-descriptions :title="this.gridData.tittle"
                           direction="vertical"
                           :column="4"
                           border>
            <el-descriptions-item label="上传者"
                                  :span="2">{{this.gridData.uploader}}</el-descriptions-item>
            <el-descriptions-item label="上传时间"
                                  :span="2">{{this.gridData.uploaddate}}</el-descriptions-item>
            <el-descriptions-item label="解答详情"
                                  :span="4">{{this.gridData.answer}}</el-descriptions-item>
          </el-descriptions>
        </el-dialog>

        <!-- 编辑问题表单 -->
        <el-dialog title="编辑"
                   :visible.sync="dialogUpdateVisible">
          <el-form :model="question"
                   status-icon
                   :rules="rules"
                   ref="question"
                   label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="问题标题"
                          prop="tittle">
              <el-input v-model="question.tittle"></el-input>
            </el-form-item>
            <el-form-item label="问题类型"
                          prop="classify">
              <el-select v-model="question.classify"
                         placeholder="请选择">
                <el-option v-for="item in options"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="解决详情"
                          prop="answer">
              <el-input type="textarea"
                        :rows="2"
                        placeholder="请输入内容"
                        v-model="question.answer">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm('question')">提交</el-button>
              <el-button @click="resetForm('question')">返回</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 新增问题表单 -->
        <el-dialog title="添加"
                   :visible.sync="dialogAddVisible">
          <el-form :model="question"
                   status-icon
                   :rules="addrules"
                   ref="question"
                   label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="问题标题"
                          prop="tittle">
              <el-input v-model="question.tittle"></el-input>
            </el-form-item>
            <el-form-item label="问题类型"
                          prop="classify">
              <el-select v-model="question.classify"
                         placeholder="请选择">
                <el-option v-for="item in options"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传者"
                          prop="uploader">
              <el-input v-model="question.uploader"></el-input>
            </el-form-item>
            <el-form-item label="解决详情"
                          prop="answer">
              <el-input type="textarea"
                        :rows="2"
                        placeholder="请输入内容"
                        v-model="question.answer">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitAddForm('question')">提交</el-button>
              <el-button @click="resetAddForm('question')">返回</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 全选、批量删除、页码 -->
      <div style="height:60px">
        <div id="common-problem-deletealldiv">
          <el-button type="danger"
                     size="small"
                     @click="handleDeleteall"
                     round>批量删除</el-button>
        </div>
        <div id="common-problem-pagediv">
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page.sync="currentpage"
                         :page-size="pagesize"
                         layout="prev, pager, next, jumper"
                         :total="totalpage">
          </el-pagination>
        </div>

      </div>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    //编辑表单校验
    var checkTittle = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      } else {
        callback();
      }
    };
    var checkClassify = (rule, value, callback) => {
      if (value == "请选择" || value == "" || !value) {
        return callback(new Error('请选择类型'));
      } else {
        callback();
      }
    };
    var checkUploader = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      } else {
        callback();
      }
    };
    var checkAnswer = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      } else {
        callback();
      }
    };
    return {
      //编辑表单校验

      rules: {
        tittle: [
          { validator: checkTittle, trigger: 'blur' }
        ],
        answer: [
          { validator: checkAnswer, trigger: 'blur' }
        ]
      },
      addrules: {
        tittle: [
          { validator: checkTittle, trigger: 'blur' }
        ],
        classify: [
          { validator: checkClassify, trigger: 'blur' }
        ],
        uploader: [
          { validator: checkUploader, trigger: 'blur' }
        ],
        answer: [
          { validator: checkAnswer, trigger: 'blur' }
        ]
      },


      //筛选
      tittlesearch: '',
      selectdate: '',
      //列表
      multipleSelection: [],
      tableData: [],
      //表单问题类型下拉选项
      options: [
        {
          value: '网页问题',
          label: '网页问题'
        },
        {
          value: '账号问题',
          label: '账号问题'
        },
        {
          value: '挂号问题',
          label: '挂号问题'
        },
      ],
      //问题详情单一对象
      gridData: {
        id: 1,
        tittle: '无',
        classify: '无',
        uploader: '无',
        display: 0,
        uploaddate: '',
        answer: ''
      },
      question: {},
      dialogTableVisible: false,
      dialogUpdateVisible: false,
      dialogAddVisible: false,
      //分页
      currentpage: 1,
      pagesize: 10,
      totalpage: 1
    }
  },
  created () {
    //列表内容请求
    this.request()
  },
  methods: {
    //列表请求封装方法
    request () {
      this.$axios({
        method: "get",
        url: "/common-problem/findProblemByPage",
        params: {
          currentpage: this.currentpage,
          pagesize: this.pagesize,
          questionsearch: this.tittlesearch,
          datesearch: this.selectdate
        }
      }).then(res => {
        this.tableData = res.data.data.records;
        this.currentpage = res.data.data.current;
        this.totalpage = res.data.data.total;
      })
    },

    //筛选
    search () {
      this.currentpage = 1;
      this.request()
    },
    //全选、反选功能
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选中改变
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    //查看详情
    checkdetail (row) {
      this.dialogTableVisible = true;
      this.gridData = row;
    },
    //编辑
    handleEdit (row) {
      this.dialogUpdateVisible = true;
      console.log(row);
      this.question = row;
      console.log(this.question);
    },
    //删除单行用户条目
    handleDelete (id, index) {
      this.$axios({
        method: "delete",
        async: false,
        url: "/common-problem/deleteProblem",
        params: {
          id: id
        }
      }).then(res => {
        if (res.data.message = "删除成功") {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
        } else {
          this.$message.error(res.data.message);
          return;
        }
        this.tableData.splice(index, 1);
        if (this.tableData.length == 0 && this.currentpage != 1) {
          this.currentpage--;
        }
        this.$axios({
          method: "get",
          url: "/common-problem/findProblemByPage",
          async: false,
          params: {
            currentpage: this.currentpage,
            pagesize: this.pagesize,
            questionsearch: this.tittlesearch,
            datesearch: this.selectdate
          }
        }).then(res => {
          this.tableData = res.data.data.records;
          this.currentpage = res.data.data.current;
          this.totalpage = res.data.data.total;
          setTimeout(
            this.$forceUpdate(), 500);
        });
      }
      )
    },
    //批量删除
    handleDeleteall (rows) {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'info',
          message: '无选中项'
        });
        return;
      }
      this.$confirm('是否确认此操作？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [];
        this.multipleSelection.forEach(problem => {
          ids.push(problem.id);
          let index = this.tableData.findIndex(function (problem) {
            return problem.index;
          });
          this.tableData.splice(index, 1);
        });
        if (this.tableData.length == 0 && this.currentpage != 1) {
          this.currentpage--;
        }
        this.multipleSelection = [];
        ;
        this.$axios({
          method: "delete",
          data: JSON.stringify(ids),
          dataType: 'json',
          url: "/common-problem/deleteSelectProblem",
          async: false,
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          }
        }).then(res => {
          if (res.data.message = "删除成功") {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
          } else {
            this.$message.error(res.data.message);
            return;
          }

          if (this.tableData.length == 0 && this.currentpage != 1) {
            this.currentpage--;
          }
          this.$axios({
            method: "get",
            url: "/common-problem/findProblemByPage",
            async: false,
            params: {
              currentpage: this.currentpage,
              pagesize: this.pagesize,
              questionsearch: this.tittlesearch,
              datesearch: this.selectdate
            }
          }).then(res => {
            this.tableData = res.data.data.records;
            this.currentpage = res.data.data.current;
            this.totalpage = res.data.data.total;
            setTimeout(
              this.$forceUpdate(), 500);
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //分页
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange (val) {
      this.request()
    },
    //改变status，是否展示
    statusSwitch (id, display) {
      this.$axios({
        method: "post",
        url: "/common-problem/updateById",
        data: {
          id: id,
          display: display,
        },
        async: false,
      });
      this.$message({
        message: '更新成功',
        type: 'success'
      });
    },
    //编辑表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "/common-problem/updateById",
            data: this.question,
          });
          this.$message({
            message: '更新成功',
            type: 'success'
          });
        } else {
          console.log('失败，请检查');
          return false;
        }
      });
    },
    resetForm (formName) {
      this.question = {};
      this.dialogUpdateVisible = false;
    },
    handleAdd () {
      this.question = {}
      this.dialogAddVisible = true;
      this.$forceUpdate();
    },
    //添加表单
    submitAddForm (formName) {
      let date = new Date();
      let uploaddate = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes();
      console.log(uploaddate);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "/common-problem/addProblem",
            data: {
              id: "0",
              tittle: this.question.tittle,
              classify: this.question.classify,
              uploader: this.question.uploader,
              display: "1",
              uploaddate: uploaddate,
              answer: this.question.answer
            },
          });
          this.$message({
            message: '添加成功',
            type: 'success'
          });

        } else {
          console.log('失败，请检查');
          return false;
        }
      });
    },
    resetAddForm (formName) {
      this.question = {};
      this.dialogAddVisible = false;
      this.$forceUpdate();
    },
  }
}
</script>
<style scoped>
* {
  /* border: 1px solid red; */
  border-radius: 3px;
}
/* 页面标题 */
#common-problem-title {
  margin-left: 50px;
  margin-right: 50px;
  height: 60px;
}
/* 筛选条件 */
#common-problem-select-div {
  margin-left: 50px;
  margin-right: 50px;
  margin-top: 10px;
  border: 1px solid gainsboro;
  border-radius: 3px;
  overflow: hidden;
}
.common-problem-select-top {
  width: 100%;
  height: 50px;
  background-color: #f0f0f0;
  line-height: 50px;
  font-size: 20px;
}
.el-icon-set-up {
  font-size: 30px;
  margin-top: 10px;
}
#common-problem-select-bottom {
  width: 100%;
  height: 100px;
  line-height: 100px;
  font-size: 20px;
}
/* 用户列表 */
#common-problem-listdiv {
  margin-left: 50px;
  margin-right: 50px;
  border: 1px solid gainsboro;
  border-radius: 3px;
  overflow: hidden;
}
.el-icon-tickets {
  font-size: 30px;
  margin-top: 10px;
}
#common-problem-problemlistdiv {
  overflow: hidden;
}
/* 批量删除 */
#common-problem-deletealldiv {
  width: 100px;
  height: 50px;
  float: left;
  margin-left: 50px;
  margin-top: 10px;
}
/* 分页 */
#common-problem-pagediv {
  height: 50px;
  float: left;
  margin-left: 200px;
  margin-top: 10px;
}
el-table-column {
  overflow: hidden;
}
</style>